import { computed, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/userStore";
import type { Comment } from "@/interface/commonData";

export default function () {
  const route = useRoute();
  const userStore = useUserStore();

  const workId = ref<number | null>(null);
  const comments = ref<Comment[]>([]);

  // 拉取评论数据
  async function REQ_getWorkComments(id: number) {
    try {
      const res = await axios.get(`/api/comment/workComment/${id}`);
      if (res.data.message === "数据为空") {
        ElMessage.info("该岗位暂无评论");
      } else {
        comments.value = res.data.data;
        console.log("评论数据：", comments.value);
      }
    } catch (error) {
      ElMessage.error("拉取评论失败");
    }
  }


  //添加一个评论
  async function REQ_addMainComment(comment: Comment) {
    try {
      const res = await axios.post("/api/comment/addMainComment", comment);
      if (res.data.message === "数据为空") {
        ElMessage.info("存储失败");
      }
      newEntry.value.id = res.data.data;
    } catch (error) {
      ElMessage.error("发布评论，请求失败");
    }
  }

  //用于表示当前的主评论
  const newEntry = ref<Comment>({
    id: null,
    jobId: null,
    parentId: null,
    userId: null,
    username: null,
    content: null,
    createTime: new Date(),
  });

  // 提交主评论
  const submitComment = async () => {
    if (!newComment.value.trim()) {
      ElMessage.error("评论内容不能为空");
      return;
    }

    let Entity: Comment = {
      id: null, // 假ID，真实场景应该用接口返回的 ID
      jobId: workId.value,
      parentId: null,
      userId: userStore.useridentityfer,
      username: userStore.username_store,
      content: newComment.value.trim(),
      createTime: new Date(),
    };

    newEntry.value = { ...Entity }
    await REQ_addMainComment(newEntry.value);
    comments.value.push(newEntry.value);
    ElMessage.success("评论成功");
    clearEntity();
  };

  //清空评论
  function clearEntity() {
    const clearEntity = {
      id: null,
      jobId: null,
      parentId: null,
      userId: null,
      username: null,
      content: null,
      createTime: new Date(),
    };
    newEntry.value = { ...clearEntity };
    newComment.value = "";
  }
  // 新建评论对象，初始化
  const newComment = ref<string>("")


  // 是否允许提交（内容非空）
  const canSubmit = computed(() => newComment.value.trim().length > 0)


  // 提交子评论（回复）
  // 有问题，父级的Id应该为著评论Id
  const handleReply = async (content: string, parent: Comment) => {
    if (!content.trim()) {
      ElMessage.error("回复内容不能为空");
      return;
    }

    if (!parent.id) {
      ElMessage.error("无效的回复目标");
      return;
    }
    let Entity: Comment = {
      id: null, // 假ID，真实场景应该用接口返回的 ID
      jobId: workId.value,
      parentId: parent.id,
      userId: userStore.useridentityfer,
      username: userStore.username_store,
      content,
      createTime: new Date(),
    };
    newEntry.value = { ...Entity }
    await REQ_addMainComment(newEntry.value);
    comments.value.push(newEntry.value);
    ElMessage.success("回复成功");
    clearEntity();

  };

  // 主评论
  const mainComments = computed(() =>
    comments.value.filter(c => c.parentId === null && c.id !== null && c.content !== null)
  );

  // 子评论
  const childComments = computed(() =>
    comments.value.filter(c => c.parentId !== null && c.id !== null && c.content !== null)
  );

  onMounted(async () => {
    const stringId = route.params.workId;
    if (typeof stringId === 'string') {
      workId.value = parseInt(stringId);
    }
    if (workId.value !== null) {
      await REQ_getWorkComments(workId.value);
      console.log("主评论：", mainComments.value);
    }
  });

  return {
    comments,
    workId,
    mainComments,
    childComments,
    newComment,
    canSubmit,
    submitComment,
    handleReply,
  };
}
